package com.duoduo.homework.h1;

import java.util.Iterator;
import java.util.NoSuchElementException;

import com.duoduo.algs4.util.ArrayUtil;

import edu.princeton.cs.introcs.StdOut;
import edu.princeton.cs.introcs.StdRandom;




public class Matrix<T> implements Iterable<T> {
	private T[][] a; 
	private int M;
	private int N;


	public T[][] getA() {
		return a;
	}

	@SuppressWarnings("unchecked")
	public T[][] transpose(T[][] a) throws Exception {

		M = a.length;
		if (M <= 0) {
			throw new Exception("数组维度应该大于0");
		}
		N = a[0].length;
		if (N <= 0) {
			throw new Exception("数组维度应该大于0");
		}
		//java 不能直接 T[][] r =  new T[N][M];
		//需要类型转换
		T[][] r = (T[][]) new Object[N][M];
		for (int i = 0; i < M; i++) {
			for (int j = 0; j < N; j++) {
				r[j][i] = a[i][j];
			}
		}
		this.a = r;
		//返回的r会是object类型
		return r;
	}

	@Override
	public Iterator<T> iterator() {
		return new DoubleArrayIterator();
	}

	private class DoubleArrayIterator implements Iterator<T> {
		private int i;
		private int j;

		public DoubleArrayIterator() {
			i = 0;
			j = 0;
		}

		public boolean hasNext() {
			return i < N && j < M;
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}

		public T next() {
			if (!hasNext())
				throw new NoSuchElementException();
			int m = j;
			int n = i;
			j++;
			if (j >= M) {
				i++;
				j = 0;
			}
			return a[n][m];
		}
	}

	public static void main(String[] args) throws Exception {
		int M = 4;
		int N = 6;
		Integer[][] a = new Integer[M][N];
		Matrix<Integer> metrix = new Matrix<Integer>();
		for (int i = 0; i < M; i++) {
			for (int j = 0; j < N; j++) {
				a[i][j] = StdRandom.uniform(0, 10);
			}
		}
		//下面的作用是循环输出数组，
		new ArrayUtil<Integer>().printDoubleArray(a);
		metrix.transpose(a);
		//
//		new ArrayUtil<Integer>().printDoubleArray(metrix.getA());
		for (Integer o : metrix) {
			StdOut.print(o + " ");
		}

	}

}
